<?php

namespace app\api\model;


use app\admin\model\User;
use app\common\library\Auth;
use app\common\library\Token;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;

class TkUser
{


    public function __construct()
    {

    }


    public static function addRobot()
    {
        $count = User::where('bio', Enum::UserStatus_Idle)->where('nickname', '机器人001')->count();
        if ($count==0) {
            $time = time();
            $robotName = 'robot_' . Random::alnum(10);
            $data = [
                'username' => $robotName,
                'password' => '123456',
                'email' => $robotName . '@a.com',
                'mobile' => '134' . Random::alnum(8),
                'level' => 1,
                'score' => 0,
                'avatar' => '',
            ];
            $params = array_merge($data, [
                'nickname' => '机器人001',
                'salt' => Random::alnum(),
                'jointime' => $time,
                'joinip' => null,
                'logintime' => $time,
                'updatetime' => $time,
                'loginip' => null,
                'prevtime' => $time,
                'bio' => Enum::UserStatus_Ready,
                'status' => 'normal'
            ]);
            $params['password'] = (new Auth())->getEncryptPassword('123456', $params['salt']);
            User::create($params, true);
        }else{
            $user = User::where('bio', Enum::UserStatus_Idle)->where('nickname', '机器人001')->limit(1)->find();
            $user['bio']=Enum::UserStatus_Ready;
            $user['updatetime']=time();
            $user->save();
        }
        new TkGame();


    }

    public static function countReadyUser():int
    {
        return User::where('bio', Enum::UserStatus_Ready)->count();

    }

    public static function getReadyUserQueue(int $count)
    {
        if(self::countReadyUser()>=$count){
            return User::where('bio', Enum::UserStatus_Ready)->order('updatetime')->limit($count)->select();
        }
    }

    public static function updateUserGo(array $users)
    {
        $ids = [];
        foreach ($users as $user){
            echo '设置用户'. $user['nickname'] .'为游戏中'. PHP_EOL;
            array_push($ids,$user['id']);
        }
        User::where('id','in',$ids)->update([
            'bio'=>Enum::UserStatus_Go
        ]);

    }

    public static function resetUserReady( )
    {

        User::where('id','>',0)->update([
            'bio'=>Enum::UserStatus_Ready
        ]);

    }



}